<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/7
 * Time: 15:18
 * 第三方短信发送平台
 */
namespace app\Service;
use app\models\Bases;

class Sms{
    protected $accountSid;
    protected $token;
    protected $message;
    public function __construct(){
        $this->accountSid = '567adcdf31ed40589476839eb91b7108';
        $this->token = '27ffc037af18488b904c6ebdd5fdccd1';
        $this->message = [
            'register'=>'立即注册',
            'updateMobile'=>'立即修改手机号码',
            'resetMobile'=>'立即重置手机号码',
            'bandMobile'=>'立即绑定手机',
            'resetPassword'=>'立即重置密码',
            'login'=>'立即登录',
            'resetImportantPwd'=>'重置交易密码',
            'chat_register' => '立即注册',
        ];
    }
    public function sendCode($data = ['action'=>'','username'=>'']){
        $this->errorMsg($data);
        $to = $data['username'];
        $time = time();
        $time = date('YmdHis',$time);
        $sig = md5($this->accountSid.$this->token.$time);
        $code = rand(100000,999999);
        cookie($data['username'].$data['action'],$code,time()+3600*15);
        $smsContent = "【国诚投顾】验证码:{$code}, 15分钟有效, {$this->message[$data['action']]}";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded','charset=utf-8'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 发送短信
        $data=array('accountSid'=>$this->accountSid,'smsContent'=>$smsContent,'to'=>$to,'timestamp'=>$time,'smsContent'=>$smsContent,'sig'=>$sig);
        curl_setopt ($ch, CURLOPT_URL, 'https://api.miaodiyun.com/20150822/industrySMS/sendSMS');
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        $json_data = curl_exec($ch);
        //将数据转换成数组
        $arr = json_decode($json_data,true);
        if($arr['respCode']=='00000'){
            $result = ['code'=>0,'errorMsg'=>'短信发送成功','sendTime'=>time()];
        }else{
            throw new \LogicException('发送短信失败',10010);
        }
        return $result;
    }
    public function errorMsg($data = array()){
        $user = new Bases('user');
        if(empty($data['action'] || empty($data['username'])))
            throw new \LogicException('参数错误',1022);
        $userInfo = $user->find("username = '{$data['username']}'");
        if($data['action'] == 'updateMobile'  || $data['action'] == 'resetPassword'){
            if(empty($userInfo)) throw  new \LogicException('该用户还未注册',10015);
        }
        if($data['action'] == 'register' || $data['action'] == 'bandMobile'){
            if(!empty($userInfo)) throw new \LogicException('你已经注册了',10018);
        }
    }
}